package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.gulimall.search.constant.ESConstant;
import com.atguigu.gulimall.search.entity.BrandEntity;
import com.atguigu.gulimall.search.feign.ProductFeignService;
import com.atguigu.gulimall.search.service.SearchService;
import com.atguigu.gulimall.search.vo.AttrRespVo;
import com.atguigu.gulimall.search.vo.SearchParam;
import com.atguigu.gulimall.search.vo.SearchResVo;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private ProductFeignService productFeignService;
    @Override
    public SearchResVo search(SearchParam param) {
        SearchResVo result = null;
        // 1.动态构建DSL语句
        SearchRequest searchRequest = buildSearchRequest(param);

        RestHighLevelClient restHighLevelClient = new GulimallElasticSearchConfig().esRestClient();

        try{
            // 2.执行检索请求
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
            // 3.分析响应数据并封装成我们需要的格式
            result = buildSearchResult(searchResponse,param);
        }catch (Exception e){
            e.printStackTrace();
        }

        return result;
    }

    // 封装DSL
    private SearchRequest buildSearchRequest(SearchParam param){
        // 1. 创建SearchRequest对象
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();// 构建DSL对象
        // 2. 构建bool查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        // 1.1 构建must查询
        if (StringUtils.isNotEmpty(param.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("skuTitle",param.getKeyword()));
        }

        // 1.2 构建filter中的catalogId查询
        if (param.getCatalog3Id() != null){
            boolQuery.filter(QueryBuilders.termQuery("catalogId",param.getCatalog3Id()));
        }

        // 1.3 构建filter中的brandId查询
        if (param.getBrandId()!=null && param.getBrandId().size()>0){
            boolQuery.filter(QueryBuilders.termsQuery("brandId",param.getBrandId()));
        }

        // 1.4 构建filter中的库存查询
        if(param.getHasStock()!=null){
            boolQuery.filter(QueryBuilders.termsQuery("hasStock",param.getHasStock()==1?true:false));
        }

        // 1.5 构建filter中的价格区间查询 -> skuPrice=100_500 or skuPrice=100_ skuPrice=_500
        if(StringUtils.isNotEmpty(param.getSkuPrice())){
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] skuPrice = param.getSkuPrice().split("_");
            if(skuPrice.length == 2){ // skuPrice=100_500
                boolQuery.filter(rangeQuery.gte(skuPrice[0]).lte(skuPrice[1]));
            } else if (skuPrice.length == 1){
                if(param.getSkuPrice().startsWith("_")){ // skuPrice=_500
                    boolQuery.filter(rangeQuery.lte(skuPrice[0]));
                }
                if(param.getSkuPrice().endsWith("_")){ // skuPrice=100_
                    boolQuery.filter(rangeQuery.gte(skuPrice[0]));
                }
            }
        }

        // 1.6 构建filter中的属性查询 attrs=1_3G:4G:5G  attrs=2_骁龙845
        if(param.getAttrs()!=null && param.getAttrs().size()>0){
            for(String attr : param.getAttrs()){
                String[] s = attr.split("_");
                BoolQueryBuilder boolQuery1 = QueryBuilders.boolQuery();
                boolQuery1.must(QueryBuilders.termsQuery("attrs.attrId",s[0]));
                String[] attrValues = s[1].split(":");
                boolQuery1.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));
                boolQuery.filter(QueryBuilders.nestedQuery("attrs",boolQuery1, ScoreMode.None));
            }
        }

        // 商城业务-检索服务-SearchRequest构建-排序、分页、高亮&测试
        // 2.1 构建 排序
        if(StringUtils.isNotEmpty(param.getSort())){
            // sort=skuPrice_asc/skuPrice_desc
            String[] s = param.getSort().split("_");
            SortOrder sortOrder = s[1].equals("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(s[0],sortOrder);
        }

        // 构建分页
        sourceBuilder.from((param.getPageNum()-1)*ESConstant.Product_PageSize);
        sourceBuilder.size(ESConstant.Product_PageSize);

        // 构建高亮
        if(StringUtils.isNotEmpty(param.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color.red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }

        // -------------------------------------------------------------------------------
        // 3.SearchRequest 构建-聚合
        // 3.1 品牌聚合
        // 3.1.1 品牌Id 聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg").field("brandId").size(50);
        // 3.1.2 品牌名 聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        // 3.1.3 品牌图片 聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brand_agg);

        // 4. 分类聚合
        // 4.1 构建分类Id聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(2);
        // 4.2 构建分类名聚合
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalog_agg);

        // 5.属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        // 4.1 构建属性Id聚合
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(50);
        // 4.1 构建属性Id下的属性名聚合
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        // 4.2 构建属性Id下的属性值聚合
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(10));
        attr_agg.subAggregation(attr_id_agg);
        sourceBuilder.aggregation(attr_agg);


        sourceBuilder.query(boolQuery);
        // 使用SearchRequest(String[] indices.SearchSourceBuilder source)这个构造器
        SearchRequest searchRequest = new SearchRequest(new String[]{ESConstant.Product_Index}, sourceBuilder);

        // 测试,打印DSL
        System.out.println("DSL:" + sourceBuilder.toString());
        return searchRequest;

    }

    // 封装响应数据
    private SearchResVo buildSearchResult(SearchResponse searchResponse,SearchParam param){

        SearchResVo searchResVo = new SearchResVo();

        // 1. 封装hit查询的所有记录
        List<SkuEsModel> skuEsModelList = new ArrayList<>();
        // 第二个hits才是封装的返回结果
        SearchHit[] hits = searchResponse.getHits().getHits();
        if(hits != null && hits.length>0){
            for (SearchHit hit : hits) {
                // source才是我们想要的内容
                String sourceAsString = hit.getSourceAsString();
                // 转化为对象
                SkuEsModel esModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                // 设置高亮
                if(StringUtils.isNotEmpty(param.getKeyword())){
                    HighlightField title = hit.getHighlightFields().get("skuTitle");
                    String s = title.getFragments()[0].toString();
                    esModel.setSkuTitle(s);
                }
                skuEsModelList.add(esModel);
            }
        }
        searchResVo.setSkuEsModels(skuEsModelList);

        // 2.封装品牌聚合信息
        List<SearchResVo.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brandAgg = searchResponse.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            SearchResVo.BrandVo brandVo = new SearchResVo.BrandVo();
            // 2.1 获取BrandId
            String brandId = bucket.getKeyAsString();
            // 2.2 获取BrandName
            ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            // 2.3 获取BrandImg
            ParsedStringTerms brandImgAgg = bucket.getAggregations().get("brand_img_agg");
            String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandId(Long.parseLong(brandId));
            brandVo.setBrandName(brandName);
            brandVo.setBrandImg(brandImg);
            brandVos.add(brandVo);
        }
        searchResVo.setBrandVos(brandVos);

        // 3.封装分类
        List<SearchResVo.CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catalogAgg = searchResponse.getAggregations().get("catalog_agg");
        for (Terms.Bucket bucket : catalogAgg.getBuckets()) {
            SearchResVo.CatalogVo catalogVo = new SearchResVo.CatalogVo();
            // 3.1 获取CatalogId
            String catalogId = bucket.getKeyAsString();
            // 3.2 获取CatalogName
            ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(catalogId));
            catalogVo.setCatalogName(catalogName);
            catalogVos.add(catalogVo);
        }
        searchResVo.setCatalogVos(catalogVos);

        // 4.封装属性
        List<SearchResVo.Attrs> attrsList = new ArrayList<>();
        ParsedNested attrAgg = searchResponse.getAggregations().get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");

        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {

            SearchResVo.Attrs attr = new SearchResVo.Attrs();
            // 4.1 获取attId
            String attrId = bucket.getKeyAsString();
            // 4.2 获取attrName
            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            String attrName = attr_name_agg.getBuckets().get(0).getKeyAsString();
            // 4.3 获取attrValues
            ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
            List<String> attrValues = attr_value_agg.getBuckets().stream().map(item -> {
                return item.getKeyAsString();
            }).collect(Collectors.toList());

            attr.setAttrId(Long.parseLong(attrId));
            attr.setAttrName(attrName);
            attr.setAttrValue(attrValues);
            attrsList.add(attr);

        }

        searchResVo.setAttrs(attrsList);

        // 封装页码
        searchResVo.setPageNum(param.getPageNum());
        // 封装总记录数
        Integer total = (int)searchResponse.getHits().getTotalHits().value;
        searchResVo.setTotalRecords(total);
        // 封装总页数
        int totalPages = total % ESConstant.Product_PageSize == 0 ? total / ESConstant.Product_PageSize : (total / ESConstant.Product_PageSize + 1);
        searchResVo.setTotalPage(totalPages);

        // 保存页码
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 0; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        searchResVo.setPageNav(pageNavs);

        // 封装面包屑导航栏的数据
        if(param.getAttrs()!=null && param.getAttrs().size()>0){
            List<SearchResVo.NavVo> navVoList = param.getAttrs().stream().map(item -> {
                SearchResVo.NavVo navVo = new SearchResVo.NavVo();
                String[] s = item.split("_");
                // 封装属性值
                navVo.setAttrValue(s[1]);
                searchResVo.getAttrIds().add(Long.parseLong(s[0]));
                // 封装属性名
                R r = productFeignService.info(Long.parseLong(s[0]));
                if(r.getCode() == 0){
                    AttrRespVo responseVo = r.getData("attr", new TypeReference<AttrRespVo>() {});
                    navVo.setAttrName(responseVo.getAttrName());
                }else{
                    // 出现异常则封装id
                    navVo.setAttrName(s[0]);
                }
                String replace = getString(param,item,"attrs");
                navVo.setLink("http://search.gulimall.com/list.html?"+replace);
                return navVo;
            }).collect(Collectors.toList());
            searchResVo.setNavs(navVoList);
        }

        // 品牌面包屑导航
        if(param.getBrandId()!=null && param.getBrandId().size()>0) {

            List<SearchResVo.NavVo> navs = searchResVo.getNavs();
            SearchResVo.NavVo navVo = new SearchResVo.NavVo();

            // 封装属性名
            navVo.setAttrName("品牌");
            R r = productFeignService.infoByIds(param.getBrandId());
            if(r.getCode() == 0){
                List<BrandEntity> brandVoList = r.getData("brand", new TypeReference<List<BrandEntity>>() {});
                StringBuffer buffer = new StringBuffer();
                String replace = "";
                for (BrandEntity brandVo : brandVoList) {
                    // 封装属性值
                    buffer.append(brandVo.getName() + ";");
                    replace = getString(param,brandVo.getBrandId() + "","brandId");
                }
                navVo.setAttrValue(buffer.toString());
                navVo.setLink("http://search.gulimall.com/list.html?"+replace);
                System.out.println("link="+navVo.getLink());
            }
            navs.add(navVo);
            searchResVo.setNavs(navs);
        }

        return searchResVo;
    }

    private static String getString(SearchParam param, String item,String key) {
        // 封装链接即去掉当前属性的查询的url封装
        String encode = null;
        try {
            encode = URLEncoder.encode(item,"UTF-8");
            encode = encode.replace("%28", "(").replace("%29", ")").replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        String replace = "";
        if(param.get_queryString().contains("&"+key+"="+encode)){
            replace = param.get_queryString().replace("&"+key+"=" + encode,"");
        }else if(param.get_queryString().contains("?"+key+"="+encode)){
            replace = param.get_queryString().replace("?"+key+"=" + encode,"");
        }
        return replace;
    }
}
